use crate::entities::{cert_info, cert_revoked_list};
use crate::repositories::cert_repository::CertRepository;
use actix_web::web::{Data, Json};
use actix_web::HttpResponse;
use attestation_common::log::{debug, error, info};
use chrono::NaiveDateTime;
use key_management::api::{impls::DefaultCryptoImpl, CryptoOperations};
use openssl::asn1::Asn1TimeRef;
use openssl::error::ErrorStack;
use openssl::nid::Nid;
use openssl::x509::{ReasonCode, X509Crl, X509};
use sea_orm::{ActiveValue, DatabaseConnection};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::sync::Arc;
use uuid::Uuid;

#[derive(Deserialize, Debug)]
pub struct QueryInfo {
    pub ids: Option<String>,
    pub cert_type: Option<String>,
}

#[derive(Debug, Deserialize, Clone)]
pub enum DeleteType {
    #[serde(rename = "id")]
    Id,
    #[serde(rename = "type")]
    Type,
    #[serde(rename = "all")]
    All,
}
#[derive(Debug, Deserialize)]
pub struct DeleteRequest {
    pub delete_type: DeleteType,
    pub ids: Option<Vec<String>>,
    #[serde(rename = "type")]
    pub cert_type: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct AddCertRequest {
    pub name: Option<String>,
    pub description: Option<String>,
    #[serde(rename = "type")]
    pub cert_type: String,
    pub content: Option<String>,
    pub is_default: Option<bool>,
    pub cert_revoked_list: Option<Vec<String>>,
}

#[derive(Debug, Deserialize)]
pub struct UpdateCertRequest {
    pub id: String,
    pub name: Option<String>,
    pub description: Option<String>,
    #[serde(rename = "type")]
    pub cert_type: Option<String>,
    pub content: Option<String>,
    pub is_default: Option<bool>,
}

#[derive(Serialize)]
pub struct QueryResponse {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
    pub certs: Vec<CertRespInfo>,
}

#[derive(Default, Serialize)]
pub struct CertRespInfo {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cert_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cert_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cert_type: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_default: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub create_time: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub update_time: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub valid_code: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cert_revoked_date: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cert_revoked_reason: Option<String>,
}

#[derive(Serialize)]
pub struct DeleteResponse {
    pub message: String,
}

#[derive(Default, Serialize)]
pub struct AddCertResponse {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cert: Option<CertRespInfo>,
}

/// 解析证书内容
pub fn parse_cert_content(content: &str) -> Result<X509, ErrorStack> {
    X509::from_pem(content.as_bytes())
}

/// 解析证书吊销列表
pub fn parse_crl_content(crl_content: &str) -> Result<X509Crl, ErrorStack> {
    X509Crl::from_pem(crl_content.as_bytes())
}

pub fn asn1_time_to_timestamp(asn1_time: &Asn1TimeRef) -> Result<i64, Box<dyn std::error::Error>> {
    // 将 Asn1Time 转换为字符串
    let time_str = asn1_time.to_string();

    // 解析时间字符串为 chrono::NaiveDateTime
    let naive_time = NaiveDateTime::parse_from_str(&time_str, "%b %e %H:%M:%S %Y GMT")?;

    // 转换为 Unix 时间戳
    Ok(naive_time.and_utc().timestamp())
}

/// 生成证书 ID
fn generate_cert_id(serial_num: &str, issuer: &str, user_id: &str) -> String {
    // 将字段组合成一个字符串
    let combined = format!("{}-{}-{}", serial_num, issuer, user_id);

    // 使用 UUID v5 生成 UUID
    let namespace = Uuid::NAMESPACE_OID; // 使用 OID 命名空间
    Uuid::new_v5(&namespace, combined.as_bytes())
        .to_string()
        .replace("-", "")
}

fn get_cert_issuer_name(cert: &X509) -> String {
    let map = cert
        .issuer_name()
        .entries()
        .into_iter()
        .map(|e| {
            (
                e.object().to_string(),
                e.data()
                    .as_utf8()
                    .map(|x| x.to_string())
                    .unwrap_or("".to_string()),
            )
        })
        .collect::<BTreeMap<String, String>>();
    serde_json::to_string(&map).unwrap_or("".to_string())
}

fn get_cert_subject_name(cert: &X509) -> String {
    let map = cert
        .subject_name()
        .entries()
        .into_iter()
        .map(|e| {
            (
                e.object().to_string(),
                e.data()
                    .as_utf8()
                    .map(|x| x.to_string())
                    .unwrap_or("".to_string()),
            )
        })
        .collect::<BTreeMap<String, String>>();
    serde_json::to_string(&map).unwrap_or("".to_string())
}

fn get_crl_issuer_name(crl: &X509Crl) -> String {
    let map = crl
        .issuer_name()
        .entries()
        .into_iter()
        .map(|e| {
            (
                e.object().to_string(),
                e.data()
                    .as_utf8()
                    .map(|x| x.to_string())
                    .unwrap_or("".to_string()),
            )
        })
        .collect::<BTreeMap<String, String>>();
    serde_json::to_string(&map).unwrap_or("".to_string())
}

struct ValidCode;

impl ValidCode {
    // 正常
    const NORMAL: i32 = 0;
    // 验签失败
    const VERIFICATION_FAILURE: i32 = 1;
    // 吊销
    const REVOKE: i32 = 2;
}

pub(crate) struct CertificateType;

impl CertificateType {
    pub(crate) const REFVALUE: &'static str = "refvalue";
    pub(crate) const POLICY: &'static str = "policy";
    pub(crate) const TPM_BOOT: &'static str = "tpm_boot";
    pub(crate) const TPM_IMA: &'static str = "tpm_ima";
    pub(crate) const CRL: &'static str = "crl";
}

pub struct CertService;

impl CertService {
    pub(crate) const MAX_NUMBER_OF_QUERIES: usize = 10;

    pub async fn get_all_certs(
        db: Data<Arc<DatabaseConnection>>,
        ids: &Option<Vec<String>>,
        cert_type: &Option<String>,
    ) -> actix_web::Result<HttpResponse> {
        info!("Handling request to get all certs");
        // 检查 ids 是否超过 10 个
        if let Some(ids) = &ids {
            if ids.len() > CertService::MAX_NUMBER_OF_QUERIES {
                error!("IDs exceed maximum limit of 10");
                return Ok(HttpResponse::Ok().json(QueryResponse {
                    message: Some(String::from("failed")),
                    certs: ids
                        .into_iter()
                        .map(|id| CertRespInfo {
                            cert_id: Some(id.clone()),
                            ..Default::default()
                        })
                        .collect(),
                }));
            }
        }
        // 校验 type 字段
        let valid_types = [
            CertificateType::REFVALUE,
            CertificateType::POLICY,
            CertificateType::TPM_BOOT,
            CertificateType::TPM_IMA,
        ];
        if let Some(cert_type) = &cert_type {
            if !valid_types.contains(&cert_type.as_str()) {
                error!("Invalid certificate type");
                return Ok(HttpResponse::Ok().json(QueryResponse {
                    message: Some(String::from("failed")),
                    certs: ids
                        .clone()
                        .unwrap_or(Vec::new())
                        .into_iter()
                        .map(|id| CertRespInfo {
                            cert_id: Some(id),
                            ..Default::default()
                        })
                        .collect(),
                }));
            }
        }

        match CertRepository::find_all(&db, ids, &cert_type).await {
            Ok(mut certs) => {
                info!("Successfully retrieved certs");
                // 查询单个/多个证书文件（Ids查询），验签，验证证书是否过期，是否被吊销，签名信息是否合法，标记valid_code，若valid_code发生变化则刷新数据库
                if ids.is_some() {
                    for (cert, cert_revoked) in &mut certs {
                        if let Some(cert_revoked_model) = cert_revoked {
                            // 校验证书吊销信息
                            let mut cert_revoked_sig = cert_revoked_model.clone();
                            cert_revoked_sig.signature = None;
                            cert_revoked_sig.key_version = None;
                            cert_revoked_sig.key_id = None;
                            cert_revoked_sig.valid_code = None;
                            if !CertService::verify_signature(
                                &cert_revoked_sig,
                                cert_revoked_model.signature.clone(),
                                cert_revoked_model.key_version.clone(),
                            )
                            .await
                                && cert_revoked_model.valid_code.eq(&Some(ValidCode::NORMAL))
                            {
                                match CertRepository::update_cert_revoked_valid_code(
                                    &db,
                                    &cert_revoked_model.id,
                                    Some(ValidCode::VERIFICATION_FAILURE),
                                )
                                .await
                                {
                                    Ok(_) => debug!("Successfully updated cert revoked"),
                                    Err(e) => error!("Failed to update cert revoked: {}", e),
                                }
                                cert_revoked_model.valid_code =
                                    Some(ValidCode::VERIFICATION_FAILURE);
                            }
                            // 更新证书信息为吊销状态
                            if !cert.valid_code.eq(&Some(ValidCode::REVOKE)) {
                                match CertRepository::update_cert_valid_code(
                                    &db,
                                    &cert.id,
                                    Some(ValidCode::REVOKE),
                                )
                                .await
                                {
                                    Ok(_) => debug!("Successfully updated cert"),
                                    Err(e) => error!("Failed to update cert: {}", e),
                                }
                                cert.valid_code = Some(ValidCode::REVOKE);
                            }
                        } else {
                            let mut cert_sig = cert.clone();
                            cert_sig.signature = None;
                            cert_sig.key_version = None;
                            cert_sig.key_id = None;
                            cert_sig.valid_code = None;
                            if !CertService::verify_signature(
                                &cert_sig,
                                cert.signature.clone(),
                                cert.key_version.clone(),
                            )
                            .await
                                && cert.valid_code.eq(&Some(ValidCode::NORMAL))
                            {
                                match CertRepository::update_cert_valid_code(
                                    &db,
                                    &cert.id,
                                    Some(ValidCode::VERIFICATION_FAILURE),
                                )
                                .await
                                {
                                    Ok(_) => debug!("Successfully updated cert"),
                                    Err(e) => error!("Failed to update cert: {}", e),
                                }
                                cert.valid_code = Some(ValidCode::VERIFICATION_FAILURE);
                            } else {
                                // 校验证书是否过期
                                let timestamp = chrono::Utc::now().timestamp();
                                if let Some(cert_content) = cert.cert_info.clone() {
                                    match parse_cert_content(&String::from_utf8_lossy(
                                        &cert_content,
                                    )) {
                                        Ok(cert_x509) => {
                                            if let Ok(expiration_time) =
                                                asn1_time_to_timestamp(cert_x509.not_after())
                                            {
                                                if expiration_time < timestamp
                                                    && cert.valid_code.eq(&Some(ValidCode::NORMAL))
                                                {
                                                    match CertRepository::update_cert_valid_code(
                                                        &db,
                                                        &cert.id,
                                                        Some(ValidCode::REVOKE),
                                                    )
                                                    .await
                                                    {
                                                        Ok(_) => {
                                                            debug!("Successfully updated cert")
                                                        }
                                                        Err(e) => {
                                                            error!("Failed to update cert: {}", e)
                                                        }
                                                    }
                                                    cert.valid_code = Some(ValidCode::REVOKE);
                                                }
                                            } else {
                                                error!("Failed to obtain the certificate expiration time.");
                                            }
                                        }
                                        Err(e) => error!("Failed to parse cert content: {}", e),
                                    }
                                }
                            }
                        }
                    }
                }
                Ok(HttpResponse::Ok().json(CertService::convert_to_query_response(certs)))
            }
            Err(e) => {
                error!("Failed to retrieve certs: {:?}", e);
                Ok(HttpResponse::Ok().json(QueryResponse {
                    message: Some(String::from("failed")),
                    certs: ids
                        .clone()
                        .unwrap_or(Vec::new())
                        .into_iter()
                        .map(|id| CertRespInfo {
                            cert_id: Some(id),
                            ..Default::default()
                        })
                        .collect(),
                }))
            }
        }
    }

    pub fn convert_to_query_response(
        certs: Vec<(cert_info::Model, Option<cert_revoked_list::Model>)>,
    ) -> QueryResponse {
        QueryResponse {
            message: None,
            certs: certs
                .into_iter()
                .map(|(cert_info, cert_revoked)| CertRespInfo {
                    cert_id: Some(cert_info.id),
                    cert_name: cert_info.name,
                    description: cert_info.description,
                    content: cert_info
                        .cert_info
                        .map(|u| String::from_utf8_lossy(&u).to_string()),
                    cert_type: cert_info.cert_type,
                    is_default: cert_info.is_default,
                    version: cert_info.version,
                    create_time: cert_info.create_time,
                    update_time: cert_info.update_time,
                    valid_code: cert_info.valid_code,
                    cert_revoked_date: cert_revoked.as_ref().and_then(|r| r.cert_revoked_date),
                    cert_revoked_reason: cert_revoked
                        .as_ref()
                        .and_then(|r| r.cert_revoked_reason.clone()),
                })
                .collect(),
        }
    }

    pub async fn delete_certs(
        db: Data<Arc<DatabaseConnection>>,
        delete_request: Json<DeleteRequest>,
    ) -> actix_web::Result<HttpResponse> {
        let delete_type = delete_request.delete_type.clone();
        let ids = delete_request.ids.clone();
        let cert_type = delete_request.cert_type.clone();

        match CertRepository::delete_certs(&db, delete_type, ids, cert_type).await {
            Ok(_) => Ok(HttpResponse::Ok().json(DeleteResponse {
                message: "success".to_string(),
            })),
            Err(e) => {
                error!("Failed to delete certs: {:?}", e);
                Ok(HttpResponse::Ok().json(DeleteResponse {
                    message: "failed".to_string(),
                }))
            }
        }
    }

    /// 校验请求并新增证书
    pub async fn add_cert(
        db: Data<Arc<DatabaseConnection>>,
        request: Json<AddCertRequest>,
        user_id: String,
    ) -> actix_web::Result<HttpResponse> {
        // 根据 type 校验必填字段
        match request.cert_type.as_str() {
            CertificateType::REFVALUE
            | CertificateType::POLICY
            | CertificateType::TPM_BOOT
            | CertificateType::TPM_IMA => {
                if request.name.is_none() || request.content.is_none() {
                    error!("Name and content are required for this type");
                    return Ok(HttpResponse::Ok().json(AddCertResponse {
                        message: Some("failed".to_string()),
                        ..Default::default()
                    }));
                }
            }
            CertificateType::CRL => {
                if request.cert_revoked_list.is_none() {
                    error!("Cert revoked list is required for CRL type");
                    return Ok(HttpResponse::Ok().json(AddCertResponse {
                        message: Some("failed".to_string()),
                        ..Default::default()
                    }));
                }
            }
            _ => {
                error!("Invalid certificate type");
                return Ok(HttpResponse::Ok().json(AddCertResponse {
                    message: Some("failed".to_string()),
                    ..Default::default()
                }));
            }
        }

        // 处理证书类型
        if request.cert_type != CertificateType::CRL {
            // 解析证书内容
            let cert_content = request.content.clone().unwrap();
            return match parse_cert_content(&cert_content) {
                Ok(cert) => {
                    if !CertService::verify_cert(&cert) {
                        error!("The imported certificate is invalid.");
                        return Ok(HttpResponse::Ok().json(AddCertResponse {
                            message: Some("failed".to_string()),
                            ..Default::default()
                        }));
                    }
                    // 获取证书序列号和颁发者
                    let serial_num = cert
                        .serial_number()
                        .to_bn()
                        .map(|n| n.to_string())
                        .unwrap_or_default();
                    let issuer = get_cert_issuer_name(&cert);
                    let owner = get_cert_subject_name(&cert);
                    // 生成证书 ID
                    let cert_id = generate_cert_id(&serial_num, &issuer, &user_id);
                    let timestamp_millis = chrono::Utc::now().timestamp_millis();
                    // 使用密钥管理进行签名
                    let cert_model_sig = cert_info::Model {
                        id: cert_id.clone(),
                        serial_num: Some(serial_num.clone()),
                        user_id: Some(user_id.clone()),
                        cert_type: Some(request.cert_type.clone()),
                        name: request.name.clone(),
                        issuer: Some(issuer.clone()),
                        owner: Some(owner.clone()),
                        cert_info: Some(cert_content.clone().into_bytes()),
                        is_default: request.is_default,
                        description: request.description.clone(),
                        version: Some(0),
                        create_time: Some(timestamp_millis),
                        update_time: Some(timestamp_millis),
                        ..Default::default()
                    };
                    let (signature, key_version) =
                        CertService::get_signature(&cert_model_sig).await;
                    // 构造 cert_info::ActiveModel
                    let cert_info = cert_info::ActiveModel {
                        id: ActiveValue::Set(cert_id.clone()),
                        serial_num: ActiveValue::Set(Some(serial_num)),
                        user_id: ActiveValue::Set(Some(user_id)),
                        cert_type: ActiveValue::Set(Some(request.cert_type.clone())),
                        name: ActiveValue::Set(request.name.clone()),
                        issuer: ActiveValue::Set(Some(issuer)),
                        owner: ActiveValue::Set(Some(owner)),
                        cert_info: ActiveValue::Set(Some(cert_content.into_bytes())),
                        is_default: ActiveValue::Set(request.is_default),
                        description: ActiveValue::Set(request.description.clone()),
                        version: ActiveValue::Set(Some(0)),
                        create_time: ActiveValue::Set(Some(timestamp_millis)),
                        update_time: ActiveValue::Set(Some(timestamp_millis)),
                        signature: ActiveValue::Set(signature),
                        key_version: ActiveValue::Set(key_version),
                        valid_code: ActiveValue::Set(Some(ValidCode::NORMAL)),
                        ..Default::default()
                    };

                    // 插入证书信息
                    if let Err(e) = CertRepository::insert_cert_info(&db, cert_info).await {
                        error!("Failed to insert cert info: {:?}", e);
                        return Ok(HttpResponse::Ok().json(AddCertResponse {
                            message: Some("failed".to_string()),
                            ..Default::default()
                        }));
                    }
                    // 返回成功响应
                    Ok(HttpResponse::Ok().json(AddCertResponse {
                        cert: Some(CertRespInfo {
                            cert_id: Some(cert_id),
                            cert_name: request.name.clone(),
                            version: Some(0),
                            ..Default::default()
                        }),
                        ..Default::default()
                    }))
                }
                Err(e) => {
                    error!("Failed to parse certificate content: {:?}", e);
                    Ok(HttpResponse::Ok().json(AddCertResponse {
                        message: Some("failed".to_string()),
                        ..Default::default()
                    }))
                }
            };
        } else {
            // 处理证书吊销列表
            let crl_list = request.cert_revoked_list.clone().unwrap();
            for crl_content in crl_list {
                // 解析证书吊销列表
                let crl = match parse_crl_content(&crl_content) {
                    Ok(crl) => crl,
                    Err(e) => {
                        error!("Failed to parse CRL content: {:?}", e);
                        return Ok(HttpResponse::Ok().json(AddCertResponse {
                            message: Some("failed".to_string()),
                            ..Default::default()
                        }));
                    }
                };
                let issuer = get_crl_issuer_name(&crl);
                if crl.get_revoked().is_none() {
                    error!("Failed to get CRL revoked");
                }
                for revoked in crl.get_revoked().unwrap() {
                    // 获取证书序列号和颁发者
                    let serial_num = revoked
                        .serial_number()
                        .to_bn()
                        .map(|n| n.to_string())
                        .unwrap_or_default();
                    // 获取吊销时间
                    let revocation_timestamp =
                        match asn1_time_to_timestamp(revoked.revocation_date()) {
                            Ok(revocation_timestamp) => revocation_timestamp,
                            Err(e) => {
                                error!("Failed to parse CRL revocation date: {:?}", e);
                                continue;
                            }
                        };
                    // 获取吊销原因
                    let reason_code = match revoked.extension::<ReasonCode>() {
                        Ok(reason) => match reason {
                            Some(reason) => reason.1.get_i64().unwrap_or(0),
                            None => {
                                continue;
                            }
                        },
                        Err(e) => {
                            error!("Failed to parse CRL revocation reason code: {:?}", e);
                            continue;
                        }
                    };
                    // 生成证书 ID
                    let cert_id = generate_cert_id(&serial_num, &issuer, &user_id);
                    // 使用密钥管理进行签名
                    let cert_revoked_model_sig = cert_revoked_list::Model {
                        id: cert_id.clone(),
                        issuer: Some(issuer.clone()),
                        serial_num: Some(serial_num.clone()),
                        user_id: Some(user_id.clone()),
                        cert_revoked_date: Some(revocation_timestamp),
                        cert_revoked_reason: Some(reason_code.to_string()),
                        ..Default::default()
                    };
                    let (signature, key_version) =
                        CertService::get_signature(&cert_revoked_model_sig).await;
                    // 构造 cert_revoked_list::ActiveModel
                    let cert_revoked = cert_revoked_list::ActiveModel {
                        id: ActiveValue::Set(cert_id),
                        issuer: ActiveValue::Set(Some(issuer.clone())),
                        serial_num: ActiveValue::Set(Some(serial_num)),
                        user_id: ActiveValue::Set(Some(user_id.clone())),
                        cert_revoked_date: ActiveValue::Set(Some(revocation_timestamp)),
                        cert_revoked_reason: ActiveValue::Set(Some(reason_code.to_string())),
                        signature: ActiveValue::Set(signature),
                        key_version: ActiveValue::Set(key_version),
                        valid_code: ActiveValue::Set(Some(ValidCode::NORMAL)),
                        ..Default::default()
                    };

                    // 插入证书吊销信息
                    if let Err(e) = CertRepository::insert_cert_revoked(&db, cert_revoked).await {
                        error!("Failed to insert cert revoked: {:?}", e);
                    }
                }
            }
        }

        // 返回成功响应
        Ok(HttpResponse::Ok().json(AddCertResponse {
            message: Some("success".to_string()),
            ..Default::default()
        }))
    }

    /// 校验请求并更新证书
    pub async fn update_cert(
        db: Data<Arc<DatabaseConnection>>,
        request: Json<UpdateCertRequest>,
        user_id: String,
    ) -> actix_web::Result<HttpResponse> {
        // 根据 type 校验必填字段
        if let Some(cert_type) = request.cert_type.clone() {
            match cert_type.as_str() {
                CertificateType::REFVALUE
                | CertificateType::POLICY
                | CertificateType::TPM_BOOT
                | CertificateType::TPM_IMA => {}
                _ => {
                    error!("Invalid certificate type");
                    return Ok(HttpResponse::Ok().json(AddCertResponse {
                        message: Some("failed".to_string()),
                        cert: Some(CertRespInfo {
                            cert_id: Some(request.id.clone()),
                            ..Default::default()
                        }),
                    }));
                }
            }
        }

        match CertRepository::find_cert_by_id(&db, &request.id).await {
            Ok(cert_info_opt) => match cert_info_opt {
                Some(cert_info_model) => {
                    if !cert_info_model
                        .user_id
                        .clone()
                        .unwrap_or("".to_string())
                        .eq(&user_id)
                    {
                        error!("No certificate update permission");
                        return Ok(HttpResponse::Ok().json(AddCertResponse {
                            message: Some("failed".to_string()),
                            cert: Some(CertRespInfo {
                                cert_id: Some(request.id.clone()),
                                ..Default::default()
                            }),
                        }));
                    }
                    let mut cert_model_sig = cert_info::Model {
                        id: cert_info_model.id.clone(),
                        serial_num: cert_info_model.serial_num.clone(),
                        user_id: cert_info_model.user_id.clone(),
                        cert_type: cert_info_model.cert_type.clone(),
                        name: cert_info_model.name.clone(),
                        issuer: cert_info_model.issuer.clone(),
                        owner: cert_info_model.owner.clone(),
                        cert_info: cert_info_model.cert_info.clone(),
                        is_default: cert_info_model.is_default.clone(),
                        description: cert_info_model.description.clone(),
                        version: cert_info_model.version.clone(),
                        create_time: cert_info_model.create_time.clone(),
                        update_time: cert_info_model.update_time.clone(),
                        ..Default::default()
                    };
                    // 解析证书内容
                    let cert_info = match request
                        .content
                        .clone()
                        .map(|cert_content| parse_cert_content(&cert_content))
                        .and_then(|r| match r {
                            Ok(cert) => Some(cert),
                            _ => None,
                        }) {
                        Some(cert) => {
                            // 获取证书序列号和颁发者
                            let serial_num = cert
                                .serial_number()
                                .to_bn()
                                .map(|n| n.to_string())
                                .unwrap_or_default();
                            let issuer = get_cert_issuer_name(&cert);
                            let owner = get_cert_subject_name(&cert);
                            // 生成证书 ID
                            let cert_id = generate_cert_id(&serial_num, &issuer, &user_id);
                            if !cert_id.eq(&request.id) {
                                error!("The certificate id does not match the certificate");
                                return Ok(HttpResponse::Ok().json(AddCertResponse {
                                    message: Some("failed".to_string()),
                                    cert: Some(CertRespInfo {
                                        cert_id: Some(request.id.clone()),
                                        ..Default::default()
                                    }),
                                }));
                            }
                            let timestamp_millis = chrono::Utc::now().timestamp_millis();

                            // 构造 cert_info::ActiveModel
                            let mut cert_info: cert_info::ActiveModel =
                                cert_info_model.clone().into();
                            if let Some(name) = request.name.clone() {
                                cert_model_sig.name = Some(name.clone());
                                cert_info.name = ActiveValue::Set(Some(name));
                            }
                            if let Some(description) = request.description.clone() {
                                cert_model_sig.description = Some(description.clone());
                                cert_info.description = ActiveValue::Set(Some(description));
                            }
                            if let Some(cert_type) = request.cert_type.clone() {
                                cert_model_sig.cert_type = Some(cert_type.clone());
                                cert_info.cert_type = ActiveValue::Set(Some(cert_type));
                            }
                            if let Some(is_default) = request.is_default.clone() {
                                cert_model_sig.is_default = Some(is_default);
                                cert_info.is_default = ActiveValue::Set(Some(is_default));
                            }
                            cert_model_sig.serial_num = Some(serial_num.clone());
                            cert_info.serial_num = ActiveValue::Set(Some(serial_num));
                            cert_model_sig.issuer = Some(issuer.clone());
                            cert_info.issuer = ActiveValue::Set(Some(issuer));
                            cert_model_sig.owner = Some(owner.clone());
                            cert_info.owner = ActiveValue::Set(Some(owner));
                            cert_model_sig.cert_info =
                                request.content.clone().map(|c| c.into_bytes());
                            cert_info.cert_info =
                                ActiveValue::Set(request.content.clone().map(|c| c.into_bytes()));
                            cert_model_sig.version =
                                Some(cert_info_model.version.clone().unwrap_or(0) + 1);
                            cert_info.version = ActiveValue::Set(Some(
                                cert_info_model.version.clone().unwrap_or(0) + 1,
                            ));
                            cert_model_sig.update_time = Some(timestamp_millis);
                            cert_info.update_time = ActiveValue::Set(Some(timestamp_millis));

                            // 使用密钥管理进行签名
                            let (signature, key_version) =
                                CertService::get_signature(&cert_model_sig).await;
                            cert_info.signature = ActiveValue::Set(signature);
                            cert_info.key_version = ActiveValue::Set(key_version);
                            cert_info
                        }
                        None => {
                            let timestamp_millis = chrono::Utc::now().timestamp_millis();
                            // 构造 cert_info::ActiveModel
                            let mut cert_info: cert_info::ActiveModel =
                                cert_info_model.clone().into();
                            if let Some(name) = request.name.clone() {
                                cert_model_sig.name = Some(name.clone());
                                cert_info.name = ActiveValue::Set(Some(name));
                            }
                            if let Some(description) = request.description.clone() {
                                cert_model_sig.description = Some(description.clone());
                                cert_info.description = ActiveValue::Set(Some(description));
                            }
                            if let Some(cert_type) = request.cert_type.clone() {
                                cert_model_sig.cert_type = Some(cert_type.clone());
                                cert_info.cert_type = ActiveValue::Set(Some(cert_type));
                            }
                            if let Some(is_default) = request.is_default.clone() {
                                cert_model_sig.is_default = Some(is_default);
                                cert_info.is_default = ActiveValue::Set(Some(is_default));
                            }
                            cert_model_sig.version =
                                Some(cert_info_model.version.clone().unwrap_or(0) + 1);
                            cert_info.version = ActiveValue::Set(Some(
                                cert_info_model.version.clone().unwrap_or(0) + 1,
                            ));
                            cert_model_sig.update_time = Some(timestamp_millis);
                            cert_info.update_time = ActiveValue::Set(Some(timestamp_millis));

                            // 使用密钥管理进行签名
                            let (signature, key_version) =
                                CertService::get_signature(&cert_model_sig).await;
                            cert_info.signature = ActiveValue::Set(signature);
                            cert_info.key_version = ActiveValue::Set(key_version);
                            cert_info
                        }
                    };
                    match CertRepository::update_cert_info(
                        &db,
                        &request.id,
                        cert_info_model.version.clone().unwrap_or(0),
                        cert_info,
                    )
                    .await
                    {
                        Ok(res) => {
                            if res.rows_affected == 1 {
                                // 返回成功响应
                                Ok(HttpResponse::Ok().json(AddCertResponse {
                                    cert: Some(CertRespInfo {
                                        cert_id: Some(request.id.clone()),
                                        cert_name: request.name.clone(),
                                        version: Some(
                                            cert_info_model.version.clone().unwrap_or(0) + 1,
                                        ),
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                }))
                            } else {
                                error!("Certificate update failure");
                                Ok(HttpResponse::Ok().json(AddCertResponse {
                                    message: Some("failed".to_string()),
                                    cert: Some(CertRespInfo {
                                        cert_id: Some(request.id.clone()),
                                        ..Default::default()
                                    }),
                                }))
                            }
                        }
                        Err(e) => {
                            error!("Certificate update failure {}", e);
                            Ok(HttpResponse::Ok().json(AddCertResponse {
                                message: Some("failed".to_string()),
                                cert: Some(CertRespInfo {
                                    cert_id: Some(request.id.clone()),
                                    ..Default::default()
                                }),
                            }))
                        }
                    }
                }
                None => {
                    error!("No corresponding certificate found");
                    Ok(HttpResponse::Ok().json(AddCertResponse {
                        message: Some("failed".to_string()),
                        cert: Some(CertRespInfo {
                            cert_id: Some(request.id.clone()),
                            ..Default::default()
                        }),
                    }))
                }
            },
            Err(e) => {
                error!("No corresponding certificate found {}", e);
                Ok(HttpResponse::Ok().json(AddCertResponse {
                    message: Some("failed".to_string()),
                    cert: Some(CertRespInfo {
                        cert_id: Some(request.id.clone()),
                        ..Default::default()
                    }),
                }))
            }
        }
    }

    pub fn verify_cert(cert: &X509) -> bool {
        // 校验证书是否过期
        let timestamp = chrono::Utc::now().timestamp();
        if let Ok(expiration_time) = asn1_time_to_timestamp(cert.not_after()) {
            if expiration_time < timestamp {
                return false;
            }
        } else {
            return false;
        }

        // 获取签名算法
        let sig_alg = cert.signature_algorithm().object();
        // 根据 OID 判断哈希算法
        let hash_algorithm = match sig_alg.nid() {
            Nid::ECDSA_WITH_SHA256 | Nid::SHA256WITHRSAENCRYPTION => Some("SHA-256"),
            Nid::ECDSA_WITH_SHA384 | Nid::SHA384WITHRSAENCRYPTION => Some("SHA-384"),
            Nid::ECDSA_WITH_SHA512 | Nid::SHA512WITHRSAENCRYPTION => Some("SHA-512"),
            _ => {
                if sig_alg.to_string().eq("SM2-with-SM3") {
                    Some("SM3")
                } else {
                    None
                }
            }
        };
        if hash_algorithm.is_none() {
            return false;
        }

        // 校验证书签名算法是否合法
        cert.public_key()
            .map(|pk| match pk.id() {
                openssl::pkey::Id::RSA => match pk.bits() {
                    2048 | 3072 | 4096 => {
                        debug!("RSA size: {:?}", pk.bits());
                        true
                    }
                    _ => false,
                },
                openssl::pkey::Id::EC => pk
                    .ec_key()
                    .map(|ec_key| {
                        ec_key
                            .group()
                            .curve_name()
                            .map(|curve_name| match curve_name {
                                Nid::X9_62_PRIME256V1 => true,
                                _ => false,
                            })
                            .unwrap_or(false)
                    })
                    .unwrap_or(false),
                _ => sig_alg.to_string().eq("SM2-with-SM3"),
            })
            .unwrap_or(false)
    }

    fn get_crypto_operations() -> impl CryptoOperations {
        DefaultCryptoImpl {}
    }

    async fn get_signature(info: &impl Serialize) -> (Option<Vec<u8>>, Option<String>) {
        let data = serde_json::to_string(info).unwrap_or("".to_string());
        debug!("get_signature:{}", data);
        let crypto_operations = CertService::get_crypto_operations();
        match crypto_operations.sign(&data.into_bytes(), "FSK").await {
            Ok(res) => (Some(res.signature), Some(res.key_version)),
            Err(_) => (None, None),
        }
    }

    async fn verify_signature(
        info: &impl Serialize,
        signature_opt: Option<Vec<u8>>,
        key_version_opt: Option<String>,
    ) -> bool {
        if let (Some(signature), Some(key_version)) = (signature_opt, key_version_opt) {
            let data = serde_json::to_string(info).unwrap_or("".to_string());
            debug!("verify_signature:{}", data);
            let crypto_operations = CertService::get_crypto_operations();
            crypto_operations
                .verify(
                    "FSK",
                    Some(key_version.as_str()),
                    data.into_bytes(),
                    signature,
                )
                .await
                .unwrap_or_else(|_| false)
        } else {
            true
        }
    }
}
